<template>
  <!--
      before-upload:文件上传时校验
      on-success:文件上传成功
   -->
  <uploadExcel :on-success="handleSuccess" />
</template>

<script>
import { reqAddEmployeeBatch } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    handleSuccess({ header, results }) {
      // 处理批量上传员工
      if (this.$route.query.type === 'user') {
        this.handleEmployee(header, results)
      }
      //   if (this.$route.query.type === 'salary') {
      //       this.handleSalary(header, results)
      //   }
      //   console.log(header, results)
    },

    async handleEmployee(header, results) {
      // 读取excel时间格式: 是以1900-1-1开始,并且计算的是天数    43535
      // js中时间戳: 1970-1-1 开始,以毫秒为单位

      // 得到数据后,批量上传员工数据
      // 已知格式: [{入职日期:43535,姓名:'jack',....},{}]
      // 上传格式: [{timeOfEntry:43535,username:'jack',....'},{}]
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }

      const newArr = []
      results.forEach(item => {
        const obj = {}
        for (const k in item) {
          const englishKey = userRelations[k]
          //   if (englishKey === 'timeOfEntry' || englishKey === 'correctionTime') {
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            obj[englishKey] = this.formatExcelDate(item[k], '-')
          } else {
            obj[englishKey] = item[k]
          }
        }
        newArr.push(obj)
      })
      // console.log(newArr)

      // ajax员工批量上传
      await reqAddEmployeeBatch(newArr)
      // 成功
      this.$message.success('批量上传员工成功')
      this.$router.push('/employees')
    },

    // 处理excel时间
    formatExcelDate(numb, format) {
      const time = new Date((numb) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
        // 2020-10-10
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
      //   20201010
    }
  }
}
</script>

<style scoped lang='scss'>

</style>
